package com.supercell.dao.impl;

import com.supercell.dao.GenericDAO;
import com.supercell.entity.GenericEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * Created by WUJO2 on 7/15/2016.
 */
public abstract class GenericDAOImpl<T extends GenericEntity> implements GenericDAO<T> {
    @Autowired
    private SessionFactory sessionFactory;

    protected abstract Class classOfT();

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings(value = "unchecked")
    @Override
    public T get(Integer id) {
        return (T) getSession().get(classOfT(), id);
    }

    @SuppressWarnings(value = "unchecked")
    @Override
    public List<T> getAll() {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(classOfT());
        detachedCriteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);
        Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
        return criteria.list();
    }

    @Override
    public Serializable save(T t) {
        return getSession().save(t);
    }

    @Override
    public void persist(T t) {
        getSession().persist(t);
    }

    @Override
    public void merge(T t) {
        getSession().merge(t);
    }

    @Override
    public void remove(Integer id) {
        getSession().delete(get(id));
    }
}
